package com.betterjr.modules.risk.loan.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.QueryTermBuilder;
import com.betterjr.modules.risk.loan.dao.LoanProjectSynchInterfaces;
import com.betterjr.modules.risk.loan.entity.LoanProjectRelation;
import com.betterjr.modules.risk.loan.entity.LoanTransactionRelation;
import com.betterjr.modules.risk.loan.field.ConfigFieldCollections;
import com.betterjr.modules.risk.loan.util.FutureUtil;
import com.betterjr.modules.risk.loan.util.HttpRequestBuilder;
import com.betterjr.modules.risk.loan.util.HttpRequestObject;

@Service
public class TransactionsLoanProjectSynchService implements LoanProjectSynchInterfaces {

    @Value("${web.prefix.fund.system.url}")
    private String prefixFundSystemUrl;

    @Autowired
    private LoanTransactionRelationService transactionRelationService;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Override
    public void InvokeDeleted(LoanProjectRelation anLoan) {

        loggerin.debug(" TransactionsLoanProjectSynchService  InvokeDeleted " + anLoan);

        String ids = getIds(anLoan.getId());
        if (StringUtils.isNoneBlank(ids)) {

            try {
                // remoteProduct(ids, ConfigFieldCollections.SAVE_CANCEL_CONFIRM_TRANSACTION_DATA_API_PATH);

                remoteProduct(ids, ConfigFieldCollections.SAVE_CANCEL_TRANSACTION_DATA_API_PATH);

            }
            catch (Exception e) {
                BTAssert.notNull(null, "远程接口调用出错" + e.getMessage());
            }
        }

    }

    /**
     * 确权交易数据放到签署合同之后进行操作
     * <p>Overriding Method of InvokeEffective</p>  
     * <p>Description: </p> 
     * @param anLoan 
     * @see com.betterjr.modules.risk.loan.dao.LoanProjectSynchInterfaces#InvokeEffective(com.betterjr.modules.risk.loan.entity.LoanProjectRelation) 
     * @author xuyp
     * @date 2018年7月14日 上午9:20:30
     */
    @Override
    public void InvokeEffective(LoanProjectRelation anLoan) {

        loggerin.debug(" TransactionsLoanProjectSynchService  InvokeEffective " + anLoan);

        // confirmTransactions(anLoan);

    }

    public void confirmTransactions(Long anLoanId) {

        loggerin.debug(" TransactionsLoanProjectSynchService  confirmTransactions " + anLoanId);
        String ids = getIds(anLoanId);
        if (StringUtils.isNoneBlank(ids)) {

            try {

                remoteProduct(ids, ConfigFieldCollections.SAVE_TRANSACTION_DATA_API_PATH);

            }
            catch (Exception e) {
                loggerin.debug("TransactionsLoanProjectSynchService远程接口交易数据调用出错" + e);
                BTAssert.notNull(null, "远程接口交易数据调用出错" + e);
            }
        }
    }

    private String getIds(Long id) {

        logger.info("LoanProjectRelationService  saveTransactionStatus 回写交易数据 贷款id=" + id);
        if (id != null && id != 0l) {
            List<LoanTransactionRelation> transactionRelations = transactionRelationService
                    .queryLoanTransactionRelations(id);
            StringBuilder sb = new StringBuilder();
            for (LoanTransactionRelation loanTransactionRelation : transactionRelations) {
                sb.append(loanTransactionRelation.getTransactionNo()).append(",");
            }

            String ids = sb.toString();
            ids = ids.substring(0, ids.length() - 1);
            return ids;
        }

        return "";
    }

    private void remoteProduct(String ids, String path) {
        HttpRequestObject requestObject = createRequest(QueryTermBuilder.newInstance().put("idList", ids).build(),
                ConfigFieldCollections.REQUEST_HTTP_METHOD_POST, path);
        FutureUtil.getHttpFuture(requestObject);

        FutureUtil.removeFuture(requestObject);
    }

    /**
     * 
     * @Title: createRequest 
     * @Description: 创建和前置系统连接的对象 
     * @param anParamMap  请求参数json
     * @param requestType  请求方法方式
     * @param apiUrl  发送httpapi路径
     * @return 
     * @throws 
     * @author xuyp
     * @date 2018年6月25日 下午5:29:34
     */
    private HttpRequestObject createRequest(Map<String, Object> anParamMap, String requestType, String apiUrl) {

        return HttpRequestBuilder.newInstance().url(prefixFundSystemUrl + apiUrl)
                .paramObject(JSONObject.toJSONString(anParamMap.values())).requestType(requestType).builder();

    }

}
